const { Msg } = require('../model')

async function createMsg({ msg, senderId, receiverId }) {
  const newMsg = await Msg.create({ msg, senderId, receiverId })
  await newMsg.save()
}

async function getHistory(req, res, next) {
  try {
    const { senderId, receiverId } = req.query
    const selfMsg = await Msg.find({ senderId, receiverId })
    const otherMsg = await Msg.find({
      senderId: receiverId,
      receiverId: senderId,
    })
    res.json({
      selfMsg,
      otherMsg,
    })
  } catch (error) {
    next(error)
  }
}

module.exports = {
  createMsg,
  getHistory,
}
